<!-- ContactList.vue - 修改HTML部分 -->
<template>
  <div class="contact-list">
    <!-- 添加发起群聊按钮 -->
    <div class="action-buttons">
      <el-button
          type="primary"
          @click="showCreateGroupDialog"
          class="create-group-btn"
      >
        <el-icon><Plus /></el-icon>
        发起群聊
      </el-button>
    </div>

    <div class="search-box">
      <el-input
          v-model="searchText"
          placeholder="搜索联系人"
          prefix-icon="Search"
          clearable
          @input="handleSearch"
      />
    </div>

    <div class="contact-items">
      <!-- 我的好友部分 -->
      <div class="contact-section">
        <div class="section-header" @click="toggleFriendSection">
          <el-icon :class="['collapse-icon', { 'is-collapsed': !friendSectionExpanded }]">
            <ArrowRight />
          </el-icon>
          <span class="section-title">我的好友</span>
        </div>

        <el-collapse-transition>
          <div v-show="friendSectionExpanded" class="section-content">
            <!-- 年级列表 -->
            <div class="grade-list">
              <div
                  v-for="grade in grades"
                  :key="grade.gradeId"
                  class="grade-item"
              >
                <div class="item-header" @click.stop="toggleGrade(grade)">
                  <el-icon :class="['collapse-icon', { 'is-collapsed': !expandedGrades[grade.gradeId] }]">
                    <ArrowRight />
                  </el-icon>
                  <span class="item-title">{{ grade.gradeName }}</span>
                </div>

                <el-collapse-transition>
                  <div v-show="expandedGrades[grade.gradeId]" class="item-content">
                    <!-- 班级列表 -->
                    <div class="class-list">
                      <div
                          v-for="classItem in getClassesByGrade(grade.gradeId)"
                          :key="classItem.classId"
                          class="class-item"
                      >
                        <div class="item-header" @click.stop="toggleClass(classItem)">
                          <el-icon :class="['collapse-icon', { 'is-collapsed': !expandedClasses[classItem.classId] }]">
                            <ArrowRight />
                          </el-icon>
                          <span class="item-title">{{ classItem.className }}</span>
                        </div>

                        <el-collapse-transition>
                          <div v-show="expandedClasses[classItem.classId]" class="item-content">
                            <!-- 学生列表 -->
                            <div v-if="getStudentsByClass(classItem.classId).length > 0">
                              <div
                                  v-for="student in getStudentsByClass(classItem.classId)"
                                  :key="student.id"
                                  class="student-item contact-item"
                                  @click.stop="selectContact(student, 'private')"
                                  :class="{ 'selected': selectedContact?.id === student.id && selectedContact?.type === 'private' }"
                              >
                                <el-avatar :size="32" :src="student.avatar" class="contact-avatar">
                                  {{ student.name?.charAt(0) || '?' }}
                                </el-avatar>
                                <div class="contact-info">
                                  <div class="contact-name">{{ student.name }}</div>
                                  <div class="contact-role">学生</div>
                                </div>
                              </div>
                            </div>

                            <!-- 加载状态 -->
                            <div v-else-if="loadingStudents[classItem.classId]" class="loading-list">
                              <el-icon class="loading-icon"><Loading /></el-icon>
                              <span>加载中...</span>
                            </div>

                            <!-- 加载按钮 -->
                            <div v-else class="empty-list">
                              <el-button
                                  type="primary"
                                  link
                                  @click.stop="loadStudentsByClass(classItem.classId)"
                              >
                                点击加载学生列表
                              </el-button>
                            </div>
                          </div>
                        </el-collapse-transition>
                      </div>
                    </div>

                    <div v-if="getClassesByGrade(grade.gradeId).length === 0" class="empty-list">
                      该年级暂无班级
                    </div>
                  </div>
                </el-collapse-transition>
              </div>
            </div>

            <!-- 所有老师列表 -->
            <div class="teacher-section">
              <div class="section-subheader" @click.stop="toggleTeacherSection">
                <el-icon :class="['collapse-icon', { 'is-collapsed': !teacherSectionExpanded }]">
                  <ArrowRight />
                </el-icon>
                <span class="item-title">所有老师</span>
              </div>

              <el-collapse-transition>
                <div v-show="teacherSectionExpanded" class="item-content">
                  <!-- 老师列表 -->
                  <div v-if="teachers.length > 0">
                    <div
                        v-for="teacher in teachers"
                        :key="teacher.id"
                        class="teacher-item contact-item"
                        @click.stop="selectContact(teacher, 'private')"
                        :class="{ 'selected': selectedContact?.id === teacher.id && selectedContact?.type === 'private' }"
                    >
                      <el-avatar :size="32" :src="teacher.avatar" class="contact-avatar">
                        {{ teacher.name?.charAt(0) || '?' }}
                      </el-avatar>
                      <div class="contact-info">
                        <div class="contact-name">{{ teacher.name }}</div>
                        <div class="contact-role">{{ teacher.teacherId ? `(${teacher.teacherId})` : '老师' }}</div>
                      </div>
                    </div>
                  </div>

                  <!-- 加载状态 -->
                  <div v-else-if="loadingTeachers" class="loading-list">
                    <el-icon class="loading-icon"><Loading /></el-icon>
                    <span>加载中...</span>
                  </div>

                  <!-- 加载按钮 -->
                  <div v-else class="empty-list">
                    <el-button
                        type="primary"
                        link
                        @click.stop="loadTeachers"
                    >
                      点击加载老师列表
                    </el-button>
                  </div>
                </div>
              </el-collapse-transition>
            </div>
          </div>
        </el-collapse-transition>
      </div>

      <!-- 我的群组部分 -->
      <div class="contact-section">
        <div class="section-header" @click="toggleGroupSection">
          <el-icon :class="['collapse-icon', { 'is-collapsed': !groupSectionExpanded }]">
            <ArrowRight />
          </el-icon>
          <span class="section-title">我的群组</span>
          <el-button
              v-if="groupSectionExpanded"
              type="primary"
              link
              size="small"
              @click.stop="refreshGroups"
              :loading="loadingGroups"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>

        <el-collapse-transition>
          <div v-show="groupSectionExpanded" class="section-content">
            <!-- 加载状态 -->
            <div v-if="loadingGroups" class="loading-list">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>加载群组中...</span>
            </div>

            <!-- 群组列表 -->
            <div v-else-if="groups.length > 0">
              <div
                  v-for="group in groups"
                  :key="group.id"
                  class="group-item contact-item"
                  @click.stop="selectContact(group, 'group')"
                  :class="{ 'selected': selectedContact?.id === group.id && selectedContact?.type === 'group' }"
              >
                <el-avatar :size="32" :src="group.avatar" class="contact-avatar" shape="square">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <div class="contact-info">
                  <div class="contact-name">{{ group.title || '未命名群组' }}</div>
                  <div class="contact-desc">
                    {{ group.type === 'group' ? '群聊' : '私聊' }}
                    · {{ group.participantCount || group.memberCount || 0 }}人
                    <span v-if="group.lastMessage" class="last-message">
                      · {{ formatLastMessage(group.lastMessage) }}
                    </span>
                  </div>
                </div>
                <!-- 未读消息提示 -->
                <div v-if="group.unreadCount > 0" class="unread-badge">
                  {{ group.unreadCount > 99 ? '99+' : group.unreadCount }}
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-list">
              暂无群组，点击右上角刷新按钮重新加载
            </div>
          </div>
        </el-collapse-transition>
      </div>
    </div>

    <!-- 创建群聊对话框 -->
    <CreateGroupDialog
        v-model:visible="showCreateGroup"
        @group-created="handleGroupCreated"
    />
  </div>
</template>

<!-- ContactList.vue - 修改JavaScript部分 -->
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowRight, User, Search, Loading, Refresh, Plus } from '@element-plus/icons-vue'
import {
  fetchUserOptions,
  fetchClassesWithGrades,
  fetchGradeList,
  fetchAllTeachers,
  getChatConversations,
  createPrivateConversation
} from '@/api/teacher'
import CreateGroupDialog from './CreateGroupDialog.vue'  // 导入对话框组件

const emit = defineEmits<{
  'contact-selected': [contact: any]
}>()

interface Grade {
  gradeId: number
  gradeName: string
}

interface Class {
  classId: number
  className: string
  gradeId: number
  gradeLevel?: string
  headTeacher?: string
  studentCount?: number
  displayName?: string
}

interface User {
  id: number
  name: string
  avatar?: string
  role: string
  class_id?: number
}

interface Teacher {
  id: number
  name: string
  username?: string
  teacherId?: string
  phone?: string
  email?: string
  avatar?: string
  college?: string
  specialty?: string
  displayName?: string
}

interface Group {
  id: number
  title?: string
  type: 'private' | 'group'
  avatar?: string
  participantCount?: number
  memberCount?: number
  unreadCount: number
  lastMessage?: any
  createdBy?: any
  updatedAt?: string
}

interface SelectedContact {
  id: number
  type: 'private' | 'group'
  name: string
}

// 搜索相关
const searchText = ref<string>('')

// 数据状态
const grades = ref<Grade[]>([])
const classes = ref<Class[]>([])
const students = ref<User[]>([])
const teachers = ref<Teacher[]>([])
const groups = ref<Group[]>([])
const selectedContact = ref<SelectedContact | null>(null)
const loadingStudents = reactive<Record<number, boolean>>({})
const loadingTeachers = ref(false)
const loadingGroups = ref(false)

// 创建群聊对话框状态
const showCreateGroup = ref(false)

// 展开/收起状态
const friendSectionExpanded = ref(true)
const groupSectionExpanded = ref(true)
const teacherSectionExpanded = ref(false)
const expandedGrades = reactive<Record<number, boolean>>({})
const expandedClasses = reactive<Record<number, boolean>>({})

// 初始化数据
onMounted(() => {
  loadInitialData()
})

// 显示创建群聊对话框
const showCreateGroupDialog = () => {
  showCreateGroup.value = true
}

// 处理群聊创建成功
const handleGroupCreated = (group: any) => {
  // 刷新群组列表
  loadGroups()

  // 可以选择自动跳转到新创建的群聊
  ElMessage.success(`群聊"${group.title}"创建成功`)

  // 可以选择自动切换到新创建的群聊
  // selectContact(group, 'group')
}

// 加载初始数据
const loadInitialData = async () => {
  try {
    // 1. 加载年级数据
    const gradesResponse = await fetchGradeList()
    if (gradesResponse.success) {
      grades.value = gradesResponse.data.map((gradeName: string, index: number) => ({
        gradeId: index + 1,
        gradeName: gradeName
      }))
    }

    // 2. 加载完整班级数据
    const classesResponse = await fetchClassesWithGrades()
    if (classesResponse.success) {
      classes.value = classesResponse.data.map((classItem: any) => ({
        classId: classItem.classId,
        className: classItem.className,
        gradeId: classItem.gradeId || extractGradeIdFromDisplayName(classItem.displayName),
        gradeLevel: classItem.gradeLevel,
        headTeacher: classItem.headTeacher,
        studentCount: classItem.studentCount,
        displayName: classItem.displayName
      }))
      updateGradeIdsFromClasses()
    }

    // 3. 加载群组数据
    await loadGroups()

  } catch (error) {
    console.error('加载通讯录数据失败:', error)
    ElMessage.error('加载通讯录数据失败')
  }
}

// 从后端加载群组数据
const loadGroups = async () => {
  try {
    loadingGroups.value = true
    const response = await getChatConversations(0, 20,'group')

    if (response.success) {
      groups.value = response.data.content.map((conversation: any) => ({
        id: conversation.id,
        title: conversation.title,
        type: conversation.type,
        avatar: conversation.avatar,
        participantCount: conversation.participants ? conversation.participants.length : 0,
        unreadCount: conversation.unreadCount || 0,
        lastMessage: conversation.lastMessage,
        createdBy: conversation.createdBy,
        updatedAt: conversation.updatedAt
      }))

      ElMessage.success(`已加载 ${groups.value.length} 个会话`)
    } else {
      ElMessage.error('加载群组数据失败')
    }
  } catch (error) {
    console.error('加载群组数据失败:', error)
    ElMessage.error('加载群组数据失败')
  } finally {
    loadingGroups.value = false
  }
}

// 刷新群组数据
const refreshGroups = async () => {
  await loadGroups()
}

// 格式化最后一条消息显示
const formatLastMessage = (lastMessage: any): string => {
  if (!lastMessage) return '暂无消息'

  const content = lastMessage.content || ''
  const senderName = lastMessage.sender?.name || '用户'

  if (lastMessage.messageType === 'text') {
    const shortContent = content.length > 15 ? content.substring(0, 15) + '...' : content
    return `${senderName}: ${shortContent}`
  }

  switch (lastMessage.messageType) {
    case 'image':
      return `${senderName}: [图片]`
    case 'file':
      return `${senderName}: [文件]`
    default:
      return `${senderName}: [消息]`
  }
}

// 从displayName中提取年级ID
const extractGradeIdFromDisplayName = (displayName: string): number => {
  const gradeMap: Record<string, number> = {
    '一年级': 1, '二年级': 2, '三年级': 3,
    '四年级': 4, '五年级': 5, '六年级': 6
  }

  for (const [gradeName, gradeId] of Object.entries(gradeMap)) {
    if (displayName?.includes(gradeName)) {
      return gradeId
    }
  }
  return 0
}

// 根据班级数据更新年级ID
const updateGradeIdsFromClasses = () => {
  const gradeNameToIdMap = new Map<string, number>()
  classes.value.forEach(classItem => {
    if (classItem.gradeLevel && classItem.gradeId) {
      gradeNameToIdMap.set(classItem.gradeLevel, classItem.gradeId)
    }
  })
  grades.value.forEach(grade => {
    const realGradeId = gradeNameToIdMap.get(grade.gradeName)
    if (realGradeId) {
      grade.gradeId = realGradeId
    }
  })
}

// 搜索处理
const handleSearch = (value: string) => {
  console.log('搜索关键词:', value)
}

// 切换好友部分展开/收起
const toggleFriendSection = () => {
  friendSectionExpanded.value = !friendSectionExpanded.value
}

// 切换群组部分展开/收起
const toggleGroupSection = () => {
  groupSectionExpanded.value = !groupSectionExpanded.value
}

// 切换老师部分展开/收起
const toggleTeacherSection = () => {
  teacherSectionExpanded.value = !teacherSectionExpanded.value
  if (teacherSectionExpanded.value && teachers.value.length === 0) {
    loadTeachers()
  }
}

// 切换年级展开/收起
const toggleGrade = (grade: Grade) => {
  const gradeId = grade.gradeId
  expandedGrades[gradeId] = !expandedGrades[gradeId]
}

// 切换班级展开/收起
const toggleClass = (classItem: Class) => {
  const classId = classItem.classId
  expandedClasses[classId] = !expandedClasses[classId]
  if (expandedClasses[classId] && getStudentsByClass(classId).length === 0) {
    loadStudentsByClass(classId)
  }
}

// 按班级加载学生数据
const loadStudentsByClass = async (classId: number) => {
  try {
    loadingStudents[classId] = true
    const response = await fetchUserOptions('', 'student', classId)
    if (response.success) {
      const classStudents = response.data || []
      students.value = students.value.filter(s => s.class_id !== classId)
      students.value.push(...classStudents.map((s: any) => ({
        ...s,
        class_id: classId
      })))
    }
  } catch (error) {
    console.error(`加载班级 ${classId} 的学生数据失败:`, error)
    ElMessage.error('加载学生数据失败')
  } finally {
    loadingStudents[classId] = false
  }
}

// 加载老师数据
const loadTeachers = async () => {
  try {
    loadingTeachers.value = true
    const response = await fetchAllTeachers()
    if (response.success) {
      teachers.value = response.data || []
    }
  } catch (error) {
    console.error('加载老师数据失败:', error)
    ElMessage.error('加载老师数据失败')
  } finally {
    loadingTeachers.value = false
  }
}

// 根据年级获取班级
const getClassesByGrade = (gradeId: number): Class[] => {
  return classes.value.filter(c => c.gradeId === gradeId)
}

// 根据班级获取学生
const getStudentsByClass = (classId: number): User[] => {
  return students.value.filter(s => s.class_id === classId)
}

// 在 ContactList.vue 中修改 selectContact 方法
// 在 ContactList.vue 中修改 selectContact 方法
const selectContact = async (contact: any, type: 'private' | 'group') => {
  try {
    // 如果是私聊，先检查或创建私聊会话
    if (type === 'private') {
      // 调用创建私聊会话的接口
      const response = await createPrivateConversation(contact.id);

      if (response.success) {
        const conversation = response.data;
        selectedContact.value = {
          id: conversation.id,
          type: 'private',
          name: contact.name
        };

        // 传递完整的私聊会话信息，包含目标用户详情
        emit('contact-selected', {
          ...conversation,
          type: 'private',
          // 添加目标用户信息
          targetUser: {
            id: contact.id,
            name: contact.name,
            avatar: contact.avatar,
            role: contact.role,
            teacherId: contact.teacherId,
            studentId: contact.studentId
          },
          // 设置私聊时的显示名称
          name: contact.name,
          avatar: contact.avatar,
          role: contact.role
        });
      } else {
        ElMessage.error('创建私聊会话失败');
      }
    } else {
      // 群聊逻辑保持不变
      selectedContact.value = {
        id: contact.id,
        type: 'group',
        name: contact.name || contact.title
      };
      emit('contact-selected', {
        ...contact,
        type: 'group'
      });
    }
  } catch (error) {
    console.error('选择联系人失败:', error);
    ElMessage.error('选择联系人失败');
  }
};


</script>

<!-- ContactList.vue - 修改CSS部分 -->
<style scoped>
.contact-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

/* 操作按钮区域 */
.action-buttons {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: center;
}

.create-group-btn {
  width: 100%;
}

.search-box {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.contact-items {
  flex: 1;
  overflow: auto;
  padding: 0 8px;
}

.contact-section {
  margin-bottom: 8px;
}

.section-header {
  display: flex;
  align-items: center;
  padding: 12px 8px;
  cursor: pointer;
  user-select: none;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.section-header:hover {
  background-color: #f5f7fa;
}

.section-title {
  flex: 1;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.section-content {
  padding-left: 16px;
}

.section-subheader {
  padding: 8px 0;
  font-weight: 500;
  color: #606266;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.section-subheader:hover {
  color: #409eff;
}

.collapse-icon {
  margin-right: 8px;
  transition: transform 0.3s;
}

.collapse-icon.is-collapsed {
  transform: rotate(90deg);
}

.grade-item,
.class-item {
  margin: 4px 0;
}

.item-header {
  display: flex;
  align-items: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.item-header:hover {
  background-color: #f5f7fa;
}

.item-title {
  flex: 1;
  font-size: 13px;
  color: #606266;
}

.item-content {
  padding-left: 20px;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin: 2px 0;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
  position: relative;
}

.contact-item:hover {
  background-color: #f5f7fa;
}

.contact-item.selected {
  background-color: #ecf5ff;
}

.contact-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.contact-info {
  flex: 1;
  min-width: 0;
}

.contact-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.contact-role,
.contact-desc {
  font-size: 12px;
  color: #909399;
}

.last-message {
  font-size: 11px;
  color: #c0c4cc;
}

.unread-badge {
  position: absolute;
  top: 8px;
  right: 12px;
  background: #f56c6c;
  color: white;
  border-radius: 10px;
  min-width: 18px;
  height: 18px;
  font-size: 11px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 4px;
}

.empty-list {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 13px;
}

.loading-list {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.loading-icon {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 滚动条样式 */
.contact-items::-webkit-scrollbar {
  width: 6px;
}

.contact-items::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.contact-items::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.contact-items::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
